import builtins
import os
import re
import shutil
from os.path import isdir

from page_editor.utils.tools import execommand


# file =

# @execommand('print(values)')
def myprint(*args,**kwargs):
    # print=os.partial(builtins.print,file=file)
    return builtins.print(*args,**kwargs)


print=myprint

def get_items(path, direct_file, pattern, level=0,subindex=''):
    '''
    :param path: 文件路径，输入要处理的文件夹
    :param direct_file: 用于把找到的文件存起来的路径
    :param level: 递归层级
    :param subindex: 序号
    :return: 该文件自己的编号
    '''
    global listnum
    if level == 0:
        listnum = 0
        direct_file = os.path.join(direct_file,'target_file')
        if not os.path.exists(direct_file):
            os.mkdir(direct_file)
    dirs = os.listdir(path) #获取所有的子文件夹和子文件
    subpath = [os.path.join(path, dir) for dir in dirs] #得到所有的地址
    if  (os.path.abspath(direct_file) in subpath):#把我们要搜索的目录中去掉用来存放目标文件的文件夹

        subpath.remove(os.path.abspath(direct_file))

    for index,each_item in enumerate(subpath):
        if isdir(each_item):
            get_items(each_item,pattern=pattern,direct_file=direct_file, level=level+1,subindex = subindex+str(index)+'.')

        else:
            basename = os.path.basename(each_item)#文件的名字

            # ^ \w + (\.pdf)$
            if re.fullmatch(pattern,basename) is not None:
                # 匹配以 .pdf结尾的所有文件
                newname = str(listnum)+'_'+basename
                # newname = basename
                # 重命名可以重写
                direct_file_name = os.path.join(direct_file,newname)
                if not os.path.exists(direct_file_name):
                    shutil.copyfile(each_item,direct_file_name)
                    # print('正在复制%s...' % basename)
                else:
                    # print('%s已存在,已经跳过...'% newname)
                    pass
                listnum+=1
    if level ==0:
        # print('复制结束,共复制{}个文件。'.format(listnum))
        pass



if __name__ == '__main__':
    ''' 
    '''



